/*
 * Copyright (C) 2009 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.locationbasedagent;



import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.OnVideoSizeChangedListener;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.TextView;


public class VideoPlayerActivity extends Activity implements
        OnBufferingUpdateListener, OnCompletionListener,
        OnPreparedListener, OnVideoSizeChangedListener, SurfaceHolder.Callback {

    private static final String TAG = "MediaPlayerDemo";
    private int mVideoWidth;
    private int mVideoHeight;
    private MediaPlayer mMediaPlayer;
    private SurfaceView mPreview;
    private SurfaceHolder holder;
    private String path;
    private Bundle extras;
    private static final String MEDIA = "media";

    private static final int STREAM_VIDEO = 5;
    private static final int RESOURCES_VIDEO = 6;

    private boolean mIsVideoSizeKnown = false;
    private boolean mIsVideoReadyToBePlayed = false;

    private int currentPosition = 0;
    
    private ImageButton mPlay;
	private ImageButton mPause;
	private ImageButton mReset;
	private ImageButton mStop;
	
	private static int TYPE = STREAM_VIDEO;  
	
	String pathToVideo;
	
    /**
     * 
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.mediaplayer_2);
        
        //Video playback requires setting up a SurfaceView and holder for the placement of the video on the screen.
        mPreview = (SurfaceView) findViewById(R.id.surface);
        holder = mPreview.getHolder();
        holder.addCallback(this);
        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
//        extras = getIntent().getExtras();
//        TYPE = extras.getInt(MEDIA);        
        
        //Example of using ImageButtons for the playback controls.
		mPlay = (ImageButton) findViewById(R.id.play);
		mPause = (ImageButton) findViewById(R.id.pause);
		mReset = (ImageButton) findViewById(R.id.reset);
		mStop = (ImageButton) findViewById(R.id.stop);
		
		//Listeners for each of the buttons.
		mPlay.setOnClickListener(playListener); 			
		mPause.setOnClickListener(pauseListener);
		mReset.setOnClickListener(rewindListener);
		mStop.setOnClickListener(stopListener); 
		
		Bundle bundle = getIntent().getExtras();
		pathToVideo = bundle.getString("videoInfo");
    }    
    
    private OnClickListener playListener = new OnClickListener() {
		public void onClick(View view) {
			//check if the MediaPlayer has not been created yet, create it with first call to playLocalMedia
			if(mMediaPlayer != null) {
				//check to either start from a given position in the file or from the beginning
				if(currentPosition != 0) 
				{
					mMediaPlayer.start();
				}
				else 
				{
					playVideo();
				}
			}
			else 
			{
				playVideo();
			}
		}
	}; 
	
	
	
	private OnClickListener pauseListener = new OnClickListener() {
		public void onClick(View view) {
			if (mMediaPlayer != null) {
				mMediaPlayer.pause();
				currentPosition = mMediaPlayer.getCurrentPosition();
			}
		}
	};
	
	private OnClickListener rewindListener = new OnClickListener() {
		public void onClick(View view) {
			if (mMediaPlayer != null) {
				mMediaPlayer.seekTo(0);
			}
		}
	};
	
	
	private OnClickListener stopListener = new OnClickListener() {
		public void onClick(View view) {
			if (mMediaPlayer != null) {
				mMediaPlayer.stop();
				mMediaPlayer.reset();
			}
			currentPosition = 0;
		}
	};

    private void playVideo() {
        doCleanUp();
        try {

//            switch (TYPE) {
//                    
//                case RESOURCES_VIDEO:
//                	//Example of playing video from the resources folder within the project.
//                	
//                	((TextView)this.findViewById(R.id.textView1)).setText("Playing Video from Resources Folder...");
//              
//                    mMediaPlayer = new MediaPlayer();
//                	String uri = "android.resource://" + getPackageName() + "/" + R.raw.sample;
//                	mMediaPlayer.setDataSource(this, Uri.parse(uri));
//                    mMediaPlayer.setDisplay(holder);
//                    mMediaPlayer.setLooping(true);
//                    mMediaPlayer.prepare();
//                    mMediaPlayer.setOnBufferingUpdateListener(this);
//                    mMediaPlayer.setOnCompletionListener(this);
//                    mMediaPlayer.setOnPreparedListener(this);
//                    mMediaPlayer.setOnVideoSizeChangedListener(this);
//                    mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
//
//                    break;
                    
 //               case STREAM_VIDEO:
                    /*
                     * TODO: Set path variable to progressive streamable mp4 or
                     * 3gpp format URL. Http protocol should be used.
                     * Mediaplayer can only play "progressive streamable
                     * contents" which basically means: 1. the movie atom has to
                     * precede all the media data atoms. 2. The clip has to be
                     * reasonably interleaved.
                     * 
                     */
        			
                    path = pathToVideo;
                    if (pathToVideo.length() > 0)
                    {
		            	((TextView)this.findViewById(R.id.textView1)).setText("Playing Streaming Video...\n" + path);
		
		                // Create a new media player and set the listeners
		                mMediaPlayer = new MediaPlayer();
		                mMediaPlayer.setDataSource(path);
		                mMediaPlayer.setDisplay(holder);
		                mMediaPlayer.prepare();
		                mMediaPlayer.setOnBufferingUpdateListener(this);
		                mMediaPlayer.setOnCompletionListener(this);
		                mMediaPlayer.setOnPreparedListener(this);
		                mMediaPlayer.setOnVideoSizeChangedListener(this);
		                mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
		            }
                    else
                    {
		            	((TextView)this.findViewById(R.id.textView1)).setText("No video path given.");

                    }
//
//                    break;
//            }
        } catch (Exception e) {
            Log.e(TAG, "error: " + e.getMessage(), e);
        }
    }

    public void onBufferingUpdate(MediaPlayer arg0, int percent) {
        Log.d(TAG, "onBufferingUpdate percent:" + percent);

    }

    public void onCompletion(MediaPlayer arg0) {
        Log.d(TAG, "onCompletion called");
    }

    public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
        Log.v(TAG, "onVideoSizeChanged called");
        if (width == 0 || height == 0) {
            Log.e(TAG, "invalid video width(" + width + ") or height(" + height + ")");
            return;
        }
        mIsVideoSizeKnown = true;
        mVideoWidth = width;
        mVideoHeight = height;
        if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) {
            startVideoPlayback();
        }
    }

    public void onPrepared(MediaPlayer mediaplayer) {
        Log.d(TAG, "onPrepared called");
        mIsVideoReadyToBePlayed = true;
        if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) {
            startVideoPlayback();
        }
    }

    public void surfaceChanged(SurfaceHolder surfaceholder, int i, int j, int k) {
        Log.d(TAG, "surfaceChanged called");

    }

    public void surfaceDestroyed(SurfaceHolder surfaceholder) {
        Log.d(TAG, "surfaceDestroyed called");
    }


    public void surfaceCreated(SurfaceHolder holder) {
        Log.d(TAG, "surfaceCreated called");
        playVideo();


    }

    @Override
    protected void onPause() {
        super.onPause();
        releaseMediaPlayer();
        doCleanUp();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        releaseMediaPlayer();
        doCleanUp();
    }

    private void releaseMediaPlayer() {
        if (mMediaPlayer != null) {
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
    }

    private void doCleanUp() {
        mVideoWidth = 0;
        mVideoHeight = 0;
        mIsVideoReadyToBePlayed = false;
        mIsVideoSizeKnown = false;
    }

    private void startVideoPlayback() {
        Log.v(TAG, "startVideoPlayback");
        holder.setFixedSize(mVideoWidth, mVideoHeight);
        mMediaPlayer.start();
    }
}
